import {createContext,useState,useContext,useEffect} from 'react'
import AsyncStorge from '@react-native-async-storage/async-storage'
import { AntDesign } from '@expo/vector-icons';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { useSelector } from 'react-redux';
const Context = createContext();
export const useToDoList = ()=>{
    return useContext(Context)
}

export const useCommendList = ()=>{
     
    return useContext(Context)
}

export const useNum = ()=>{
     
    return useContext(Context)
}

const getCurrentDay = () =>{
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate;
    }
    let currentdate = year + '-' + month + '-' + strDate;
    return currentdate;
}

const compare = (date1,date2) =>{
    let arr1 = date1.split('-');//小日期
    let arr2 = date2.split('-');//大日期
    let year = arr2[0] - arr1[0];
    let month = arr2[1] - arr1[1];
    let day = arr2[2] - arr1[2];
    if(year==0&&month==0&&day==0){
        return 0;
    }
    if(year==0&&month==0&&day==1){
        return 1;
    }
    if(year==0&&month==1&&day<0){
        return 1;
    }
    if(year==1&&month<0&&day<0){
        return 1;
    }
}


const Provider = (props) => {
    const list=useSelector(state=>state.list)
    const [todoList,setToDoList]=useState([]);
    const [num0,setNum0] = useState(0);
    const [commendList,setCommendList] = useState(list);
    useEffect(()=>{
     
            fetch('https://wx.qasdwer.top:8080/share/getshare')
            .then(res=>res.json())
            .then(res=>setCommendList(res))

        AsyncStorge.getItem('getToDoList').then(res=>{
            if(res){
                setToDoList(JSON.parse(res))
            }
        })

        AsyncStorge.getItem('words').then(res=>{
            if(res){
                let time = JSON.parse(res).date;
                let date = getCurrentDay();
                let x = compare(time,date);
                if(x == 0){
                    setNum0(JSON.parse(res).num)
                }else{
                    setNum0(0);
                }
            }
        })
    },[])
    return <Context.Provider value={{todoList,setToDoList,commendList,setCommendList,num0,setNum0}}>
        {props.children}
    </Context.Provider>
}
export default Provider